﻿using dotnet2cache.Abstractions.Bus;
using dotnet2cache.Abstractions.Serialization;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;



namespace dotnet2cache.CsRedis
{
    class RedisBus : IMessageBus
    {
        private static String ServerID;

        static RedisBus()
        {
            ServerID = Guid.NewGuid().ToString("N");
        }

        //private IDataSerializer _dataSerializer;

        //public RedisBus(IDataSerializer dataSerializer)
        //{
        //    _dataSerializer = dataSerializer;
        //}

        public void Publish(string topic, Message message)
        {
            BusRedisHelper.LPush(topic, message);
        }

        public async Task PublishAsync(string topic, Message message, CancellationToken cancellationToken = default)
        {
            if(cancellationToken.IsCancellationRequested)
            {
                return;
            }

          await  BusRedisHelper.LPushAsync(topic, message);
        }

        public void Subscribe(string topic, Action<Message> action)
        {
            BusRedisHelper.SubscribeListBroadcast(topic, ServerID, (msg) => {
                if(string.IsNullOrEmpty(msg))
                {
                    return;
                }

                var message = JsonConvert.DeserializeObject<Message>(msg);
                if(message==null)
                {
                    return;
                }

                action?.Invoke(message);

            });
        }
    }
}
